|
|
|
|
|
|
|
Figure 15.14.
Results of a multitable DELETE. |
|
|
|
|
|
|
|
|
The results of this DELETE query might surprise you. Because there is no WHERE clause in the DELETE statement that could limit the scope of the SQL command, you might think that the statement deletes all records in both tables. In fact, this statement only deletes the records that have a matching RecID in both tables. The reason for this is that you used an INNER JOIN. INNER JOIN clauses operate only on records that appear in both tables. You now have an excellent way to remove records from multiple tables with one DELETE statement! It must be pointed out, however, that this technique only works with tables that have a one-to-one relationship defined. In the case of one-to-many relationships, only the first occurrence of the match on the many side is removed. |
|
|
|
|
|
|
|
|
Here is a puzzle for you. What happens if you only list Table1 in the first part of that last DELETE statement? |
|
|
|
|
|
|
|
|
DELETE Table1.* FROM
Table1 INNER JOIN Table2 ON Table1.RecID = Table2.RecID; |
|
|
|
|
|
|
|
|
What records (if any) are deleted from Table1? Edit SQLVB08.SQV, save it, and execute it to find out. Check your results against Figure 15.15. |
|
|
|
|
|
|
|
|
As you can see from Figure 15.15, a DELETE query that contains an INNER JOIN only removes records from Table1 that have a match in Table2. And the records in Table2 are left intact! This is a good example of using JOIN clauses to limit the scope of a DELETE statement. This technique is very useful when you want to eliminate duplicates in related or identical tables. Note also that this INNER JOIN works just fine without the use of defined constraints or index keys. |
|
|
|
|
|